!function(root, factory) {
  if(typeof define == 'function' && define.amd) {
    define(['jquery'], factory)
  } else if(typeof exports == 'object') {
    factory(require('jquery'))
  } else {
    factory(root.jQuery)
  }
}(this, function($) {
  
  'use strict';
  
  $.fn.ajaxtab = function(option) {
    
    var options = $.extend({
      loadingMessage: '正在加载数据...',
      successMessage: '加载数据成功',
      failureMessage: '加载数据失败',
      errorMessage: '加载数据失败',
      beforeSubmit: null,
      success: null,
      failure: null,
    },option)
    
    var backdrop = '<div class="ajaxtab-backdrop fade">' +
                       '<div class="backdrop-content">' +
                         '<p><span class="icon icon-loader"></span>' +
                           options.loadingMessage +
                         '</p>' +
                       '</div>' +
                     '</div>';
    
    // 初始化内容区块
    function initContent(content, tabs) {
      
      if(!$(content).length) // 如果content不存在， 在ul后面添加content
        $(el).after("<div id='" + content.split("#")[1] + "' class='tab-conetnt'></div>");
      
      var conetntTemplate = "<div class='tab-pane fade'></div>";
      
      $(tabs).each(function(index) {  //初始化按钮的target content 区块
        
        var $targetContent = $(tabs[index]).data("target");
        if($($targetContent).length) {
          $(tabs[index]).data("status", "loaded");
        }else {
          $(conetntTemplate).appendTo(content).attr("id", $targetContent.split("#")[1]);
          $(tabs[index]).data("status", "unload"); 
        }
      })
    }
    
    // 改变消息
    var changeBackdropMessage = function($backdrop, message, clazz, callback) {
      $backdrop.find('p').html('<strong>' + message + '</strong>')
                         .addClass(clazz ? clazz : '')
      callback && callback(el, $backdrop[0], message)
    }
    
    // ajax 加载区块内容
    function ajaxLoad(content, tab) {
      
      // 固定content高度，用于展示加载
      $(content).css("min-height", "200px");
      
      var $url = $(tab).attr("href");
      var $target = $(tab).data('target');
      
      if(options.hasOperation) {
        var $operation = $(tab).data('operation') || "#" + $(tab).attr("id") + "-operation";
      }
      
      var $backdrop = $(backdrop).appendTo(content).addClass("in");
      
      $.get($url).done(function(data) {
        
        setTimeout(function(){
          changeBackdropMessage($backdrop, data.message || options.successMessage, 'text-success', options.success)
        }, 300)
        
        $(tab).parent().addClass("active");
        $($target).empty().append(data).addClass("active").addClass("in");
        
        $($target).trigger("ajax:load:success");
        
        if(options.hasOperation && $operation) $($operation).removeClass("hide");
        
        setTimeout(function(){
          $(tab).data("loaded", true);
          $backdrop.removeClass("in");
          $(content).css("min-height", "0px");
        }, 700)
        
      }).fail(function() {
        $(tab).data("loaded", false);
        changeBackdropMessage($backdrop, options.failureMessage, 'text-danger');
        
        setTimeout(function(){
          $backdrop.removeClass("in");
          
          $($target).empty().append("<p style='text-align: center; margin: 50px 0;'>加载数据出现异常，请稍后重试</p>");
          
          $(content).css("min-height", "0px");
          
        }, 700)
        
      });
    }
    
    // 执行加载
    function refresh(tab) {
      var content = $(tab).data('warp');
      var tabs = $(tab).data("tabs");
      // 隐藏所有
      hideOperations(tabs);
      ajaxLoad(content, tab);
      $(tab).trigger("refresh:success")
    }
    
    // 隐藏操作，可单个或多个
    function hideOperations(targets) {
      if(typeof targets === 'string') {
        var $targetOperation = $(targets).data("operation") || "#" + $(targets).attr("id") + "-operation";
        if($targetOperation) $($targetOperation).addClass("hide");
      }else {
        targets.each(function(index) {
          var $targetOperation = $(targets[index]).data("operation") || "#" + $(targets[index]).attr("id") + "-operation";
          if($targetOperation) $($targetOperation).addClass("hide");
        })
      }
    }
    
    function init(el){
      
      var tabs = $(el).find('a[data-toggle="tab"]');
      var activetab = $(el).find('li.active a');
      var content = $(el).data("content") || '#' + $(el).attr("id") + '-content';
      
      
      var operation= $(el).data("operation")
      
      if($(el).data("operation") != null)  {
        options.hasOperation = true;
      }
      
      options.tabs = tabs;
      options.content = content;
      
      $(el).data("options", options);
      
      //执行内容初始化
      initContent(content, tabs);
      
      //执行选中状态初始化
      if(activetab.length) {  // 显示当前选中的区块
        var $targetContent = $(activetab[0]).data("target");
        if(options.hasOperation) {
          var $targetOperation = $(activetab[0]).data("operation") || "#" + $(activetab[0]).attr("id") + "-operation";
          if($targetOperation) $($targetOperation).removeClass("hide");
        }
        
        $($targetContent).addClass("in");
        $(activetab[0]).data('loaded', true);
        
      }else {  // 远程加载第一个区块，并显示
        if(options.hasOperation) hideOperations(tabs);
        ajaxLoad(content, tabs[0]);
      }
      
      // 绑定bootstrap tab 事件
      $(tabs).on('show.bs.tab', function (e) {
        
        // 隐藏所有
        if(options.hasOperation) hideOperations(tabs);
        
        var refresh = $(this).data("refresh");
        
        if($(this).data("refresh") == true) {
          ajaxLoad(content, this);
        }else {
          if(!$(this).data("loaded")) { //未加载的区块进行加载
            ajaxLoad(content, this);
          }else { //已加载区块同步operation
            
            if(options.hasOperation) {
              var $operation = $(this).data('operation') || "#" + $(this).attr("id") + "-operation";
              $($operation).removeClass("hide");
            }
          }
        }
      })
      
      if(options.hasOperation) {
        // 为每一个operation 绑定 refresh事件
        $(tabs).each(function(index) {
          $(this).data('warp', content);
          $(this).data('tabs', tabs)
          $(this).on('ajax:load:refresh', function(){
            refresh($(this));
          })
        })
      }
    }
    
    return this.each(function() {
      init(this)
    })
    
  }
  
  $.fn.ajaxtab.noConflict = function() {
    $.fn.ajaxtab = old
    return this
  }
  
})